package com.jastar.android.test.demo;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.jastar.android.test.R;
import com.jastar.android.tts.BaiduTTSConfig;
import com.jastar.android.tts.BaiduTTSManager;
import com.jastar.android.util.FileUtil;
import com.jastar.android.util.RandomUtil;

import java.util.ArrayList;
import java.util.List;

public class SpokenStudyActivity extends AppCompatActivity implements View.OnClickListener {

    private List<String> spokenSentences;
    private TextView tvEnglish;
    private TextView tvChinese;
    private String currentEnglish;
    private String currentChinese;
    private BaiduTTSManager ttsManager;
    private Handler handler;
    private boolean isPlaying = false; // 添加标记变量，指示是否正在朗读
    private View buttonRepeat, buttonNext; // 添加按钮引用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spoken_study);

        tvEnglish = findViewById(R.id.tv_english);
        tvChinese = findViewById(R.id.tv_chinese);
        buttonRepeat = findViewById(R.id.button_repeat);
        buttonNext = findViewById(R.id.button_next);
        buttonRepeat.setOnClickListener(this);
        buttonNext.setOnClickListener(this);

        // 初始化百度TTS管理器
        ttsManager = BaiduTTSManager.initInstance(this);
        handler = new Handler();

        // 读取英语口语句子文件
        int moduleIndex = 0;
        spokenSentences = new ArrayList<>();
        List<String> lines = FileUtil.readRawLines(getResources(), R.raw.kinder_spoken_english);
        for (String line : lines) {
            if (line.startsWith("#")) moduleIndex++;
            if (moduleIndex > 4) break; //moduleIndex从1开始
            if (!line.startsWith("#") && !line.trim().isEmpty()) {
                spokenSentences.add(line);
            }
        }

        // 显示第一个随机句子
        showNextSentence();
    }

    @Override
    public void onClick(View v) {
        if (!isPlaying) { // 只有当不在朗读时才响应按钮点击
            if (v.getId() == R.id.button_repeat) {
                // 重读当前句子
                readCurrentSentence();
            } else if (v.getId() == R.id.button_next) {
                // 显示下一个随机句子
                showNextSentence();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 移除所有待处理的任务
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放Handler资源
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    // 显示下一个随机句子
    private void showNextSentence() {
        if (spokenSentences.isEmpty()) return;

        // 随机获取一个句子
        String line = spokenSentences.get(RandomUtil.random.nextInt(spokenSentences.size()));
        // 解析句子，格式：序号|英文|中文
        String[] parts = line.split("\\|");
        if (parts.length >= 3) {
            currentEnglish = parts[1];
            currentChinese = parts[2];

            // 显示英文和中文
            tvEnglish.setText(currentEnglish);
            tvChinese.setText(currentChinese);

            // 读出英文句子
            readCurrentSentence();
        }
    }

    // 读出当前英文和中文句子，中间添加停顿
    private void readCurrentSentence() {
        if (currentEnglish == null || currentEnglish.isEmpty() || ttsManager == null) {
            return;
        }

        // 标记开始朗读，禁用按钮
        isPlaying = true;
        buttonRepeat.setEnabled(false);
        buttonNext.setEnabled(false);

        final String per = BaiduTTSConfig.PERS[(int) (Math.random() * BaiduTTSConfig.PERS.length)]; // 两个PER随机选择一个

        handler.postDelayed(() -> ttsManager.speak(currentEnglish, per, new BaiduTTSManager.TTSListener() {
            @Override
            public void onDone() {
                handler.postDelayed(() -> ttsManager.speak(currentChinese, per, new BaiduTTSManager.TTSListener() {
                    @Override
                    public void onDone() {
                        enableButtonsAfterPlayback();
                    }

                    @Override
                    public void onError(String error) {
                        enableButtonsAfterPlayback();
                    }
                }), 1000);
            }

            @Override
            public void onError(String error) {
                enableButtonsAfterPlayback();
            }
        }), 300);
    }

    private void enableButtonsAfterPlayback() {
        isPlaying = false;
        buttonRepeat.setEnabled(true);
        buttonNext.setEnabled(true);
    }

}